package com.heima.user.service.impl;

import com.heima.common.exception.CustException;
import com.heima.model.common.constants.user.UserRelationConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.dtos.UserRelationDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.ApUserRelationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ApUserRelationServiceImpl implements ApUserRelationService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public ResponseResult follow(UserRelationDTO dto) {
        // 1 检查参数(是否登录 operation的值 必须是 0 1)
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        Short operation = dto.getOperation();
        if (operation.intValue()!=0&& operation.intValue()!=1){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        ZSetOperations<String, String> oper = redisTemplate.opsForZSet();
        // 如果是0 要关注
        if (operation.intValue()==0){
            // 判断是否已经关注 ZSCORE
            Double score = oper.score(UserRelationConstants.FOLLOW_LIST + user.getId(), String.valueOf(dto.getAuthorApUserId()));
            if (score!=null){
                CustException.cust(AppHttpCodeEnum.DATA_EXIST,"请勿重复关注");
            }
            // 是否自己关注自己
            if (user.getId().equals(dto.getAuthorApUserId())){
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"请勿关注自己");
            }
            // 关注 zadd follow: 登录用户id  作者id  zadd fans:作者id 登录用户id
            // key       value  score
            oper.add(UserRelationConstants.FOLLOW_LIST+user.getId()
                    ,String.valueOf(dto.getAuthorApUserId())
                    ,System.currentTimeMillis());
            oper.add(UserRelationConstants.FANS_LIST+dto.getAuthorApUserId(),
                    String.valueOf(user.getId()),
                    System.currentTimeMillis());
        }else {

            // 如果是1 要取关
            // 取关 zrem follow:登录用户id  作者用户id zrem fans:作者id 登录用户id
            oper.remove(UserRelationConstants.FOLLOW_LIST+user.getId(),
                    String.valueOf(dto.getAuthorApUserId())
                   );
            oper.remove(UserRelationConstants.FANS_LIST+dto.getAuthorApUserId(),
                    String.valueOf(user.getId()));
        }

        return ResponseResult.okResult();
    }
}
